package com.rc.saas.mini.service.member;

import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.mapper.car.TenantCarNumberMapper;
import com.rc.saas.mini.mapper.member.MemberAccountMapper;
import com.rc.saas.mini.mapper.member.MemberAccountRecordMapper;
import com.rc.saas.mini.mapper.member.MemberInfoMapper;
import com.rc.saas.mini.mapper.tenant.TenantMapper;
import com.rc.saas.mini.model.enterprise.*;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberAccountRecord;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.member.MemberInfoExample;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.ugs.*;
import com.rc.saas.mini.search.TenantDiscountSearch;
import com.rc.saas.mini.service.discount.TenantDiscountTimeService;
import com.rc.saas.mini.service.elec.EnterpriseSubmemberService;
import com.rc.saas.mini.service.enterprise.EnterpriseMemberService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberApplyService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberOutService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberRecordService;
import com.rc.saas.mini.service.rc.RcMemberFlagService;
import com.rc.saas.mini.service.recharge.RechargeOrderServiceImpl;
import com.rc.saas.mini.service.tenant.TenantOpenServiceService;
import com.rc.saas.mini.service.ugs.TenantUgsLevelGainService;
import com.rc.saas.mini.service.ugs.TenantUgsMemberLevelService;
import com.rc.saas.mini.service.ugs.UgsMemberSuperLevelService;
import com.rc.saas.mini.vo.member.MemberSuperLevelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/12/15
 */
@Service
public class MemberInfoServiceImpl implements MemberInfoService {

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private TenantOpenServiceService tenantOpenServiceService;

    @Autowired
    private TenantUgsLevelGainService tenantUgsLevelGainService;

    @Autowired
    private TenantUgsMemberLevelService tenantUgsMemberLevelService;

    @Autowired
    private EnterpriseSubmemberService enterpriseSubmemberService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private TenantDiscountTimeService tenantDiscountTimeService;

    @Autowired
    private UgsMemberSuperLevelService ugsMemberSuperLevelService;

    @Autowired
    private EnterpriseSubmemberOutService enterpriseSubmemberOutService;

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private EnterpriseSubmemberRecordService enterpriseSubmemberRecordService;

    @Autowired
    private TenantCarNumberMapper tenantCarNumberMapper;

    @Autowired
    private RcMemberFlagService rcMemberFlagService;


    @Autowired
    private RechargeOrderServiceImpl rechargeOrderServiceImpl;

    @Override
    public MemberInfoMapper getMapper() {
        return memberInfoMapper;
    }

    @Override
    public MemberInfo selectMemberByUnionid(String unionid, String tenantCode) {
        MemberInfoExample example = new MemberInfoExample();
        MemberInfoExample.Criteria criteria = example.createCriteria();
        criteria.andWechatUnionidEqualTo(unionid);
        if (tenantCode != null) {
            criteria.andTenantCodeEqualTo(tenantCode);
        }
        return memberInfoMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public MemberInfo selectMemberByOpenid(String openid, String tenantCode) {
        MemberInfoExample example = new MemberInfoExample();
        MemberInfoExample.Criteria criteria = example.createCriteria();
        criteria.andMinipOpenidEqualTo(openid);
        if (tenantCode != null) {
            criteria.andTenantCodeEqualTo(tenantCode);
        }
        return memberInfoMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public MemberInfo selectByMobile(String mobile, String tenantCode) {
        MemberInfoExample example = new MemberInfoExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andMobileEqualTo(mobile);
        return memberInfoMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public void createRegisterWithMobile(MemberInfo member) {
        //member
        memberInfoMapper.insertReturnId(member);
        //member_account_record
        Tenant tenant = tenantMapper.selectByPrimaryKey(member.getTenantCode());
        //member_account
        MemberAccount memberAccount = new MemberAccount();
        //注册赠送金额
        if (tenant.getRegisteGiveAmount().doubleValue() > 0) {
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(member.getTenantCode());
            memberAccountRecord.setMemberId(member.getMemberId());
            memberAccountRecord.setAccountType("0");
            memberAccountRecord.setRecordType("5");
            memberAccountRecord.setAmount(tenant.getRegisteGiveAmount());
            memberAccountRecord.setResult(tenant.getRegisteGiveAmount());
            memberAccountRecord.setCreatedTime(member.getCreatedTime());
            memberAccountRecord.setRemark("注册平台赠送");
            memberAccountRecord.setLastUpdatedTime(new Date());
            memberAccountRecord.setCreatedTime(new Date());
            memberAccountRecordMapper.insertSelective(memberAccountRecord);

            memberAccount.setAccount(tenant.getRegisteGiveAmount());
            memberAccount.setMemberId(member.getMemberId());
            memberAccount.setTenantCode(member.getTenantCode());
            memberAccount.setAccount(BigDecimal.ZERO);
            memberAccount.setGiveAccount(BigDecimal.ZERO);
            memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
            memberAccount.setAllTransferAmount(BigDecimal.ZERO);
            memberAccount.setPoint(0);
            memberAccount.setCreatedTime(new Date());
            memberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.insertSelective(memberAccount);
        } else {
            //新增member_account
            memberAccount.setMemberId(member.getMemberId());
            memberAccount.setTenantCode(member.getTenantCode());
            memberAccount.setAccount(BigDecimal.ZERO);
            memberAccount.setGiveAccount(BigDecimal.ZERO);
            memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
            memberAccount.setAllTransferAmount(BigDecimal.ZERO);
            memberAccount.setPoint(0);
            memberAccount.setCreatedTime(new Date());
            memberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.insertSelective(memberAccount);
        }

        //会员标签设置
        rcMemberFlagService.insertByRegister(member);
        ////会员默认等级
        //rechargeOrderServiceImpl.rcMemberLevelSettingAdd(memberAccount);
    }

    @Override
    public MemberSuperLevelVo selectMemberSuperLevel(MemberInfo memberInfo) {

        MemberSuperLevelVo memberSuperLevelVo = new MemberSuperLevelVo(memberInfo);
        TenantDiscountSearch tenantDiscountSearch = new TenantDiscountSearch();
        tenantDiscountSearch.setTenantCode(memberInfo.getTenantCode());
        if (memberInfo != null && memberInfo.getMemberId() != null) {

            tenantDiscountSearch.setMemberId(memberInfo.getMemberId());
            //是否启用会员等级
            boolean isLevel = tenantOpenServiceService.isServiceTypeCode(memberInfo.getTenantCode(), "LEVEL");
            //是否启用超级会员等级
            boolean isSvip = tenantOpenServiceService.isServiceTypeCode(memberInfo.getTenantCode(), "SVIP");

            //添加权益设置tenant_ugs_level_gain
            TenantUgsLevelGainExample example = new TenantUgsLevelGainExample();
            example.createCriteria().andTenantCodeEqualTo(memberInfo.getTenantCode()).andStatusEqualTo("0");
            List<TenantUgsLevelGain> tenantUgsLevelGains = tenantUgsLevelGainService.selectByExample(example);

            boolean isV = tenantUgsLevelGains.stream().filter(tenantUgsLevelGain -> "V".equals(tenantUgsLevelGain.getLvType())).findFirst().isPresent();
            boolean isL = tenantUgsLevelGains.stream().filter(tenantUgsLevelGain -> "L".equals(tenantUgsLevelGain.getLvType())).findFirst().isPresent();


            if (isSvip && isV) {
                //超级会员 ugs_member_super_level
                memberSuperLevelVo.setUgsMemberSuperLevel(selectUgsMemberSuperLevel(memberInfo));
            } else {
                memberSuperLevelVo.setUgsMemberSuperLevel(null);
            }
            //会员等级 tenant_ugs_member_level
            if (isLevel && isL) {
                //用户等级自动生成
                tenantUgsMemberLevelService.insertTenantUgsMemberLevel(memberInfo);
                tenantUgsMemberLevelService.updateReduceLevel(memberInfo.getMemberId());
                memberSuperLevelVo.setTenantUgsMemberLevel(selectTenantUgsMemberLevel(memberInfo));

            } else {
                memberSuperLevelVo.setTenantUgsMemberLevel(null);
            }

            boolean flagEnt = false;
            //子会员
            if ("2".equals(memberInfo.getMemberType())) {
                EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberService.selectByPrimaryKey(memberInfo.getMemberId());
                flagEnt = enterpriseSubmember != null && "0".equals(enterpriseSubmember.getStatus());
            }
            //用户主会员
            if ("1".equals(memberInfo.getMemberType())) {
                EnterpriseMember enterpriseMember = enterpriseMemberService.selectByMemberId(memberInfo.getMemberId());
                flagEnt = enterpriseMember != null && "0".equals(enterpriseMember.getStatus());
            }
            //企业优惠
            if (flagEnt) {
                tenantDiscountSearch.setEnterpriseId(memberInfo.getEnterpriseMemberId());
                List<TenantDiscountSearch> enterpriseDiscount = tenantDiscountTimeService.listEnterpriseDiscountBySearch(tenantDiscountSearch);
                if (enterpriseDiscount.size() > 0) {
                    memberSuperLevelVo.setEnterpriseDiscount(enterpriseDiscount);
                }
            }
        }

        //桩群优惠(不包括企业优惠)
        List<TenantDiscountSearch> stationDiscount = tenantDiscountTimeService.listDiscountStationBySearchNotEnt(tenantDiscountSearch);
        if (stationDiscount != null && stationDiscount.size() > 0) {
            memberSuperLevelVo.setStationDiscount(stationDiscount);
        }
        return memberSuperLevelVo;
    }

    @Override
    public TenantUgsMemberLevel selectTenantUgsMemberLevel(MemberInfo memberInfo) {
        //会员等级 tenant_ugs_member_level
        TenantUgsMemberLevelExample tenantUgsMemberLevelExample = new TenantUgsMemberLevelExample();
        tenantUgsMemberLevelExample.createCriteria().andMemberIdEqualTo(memberInfo.getMemberId()).andTenantCodeEqualTo(memberInfo.getTenantCode());
        List<TenantUgsMemberLevel> tenantUgsMemberLevels = tenantUgsMemberLevelService.selectByExample(tenantUgsMemberLevelExample);
        return tenantUgsMemberLevels.stream().findFirst().orElseGet(() -> null);
    }


    @Override
    public UgsMemberSuperLevel selectUgsMemberSuperLevel(MemberInfo memberInfo) {
        //超级会员 ugs_member_super_level
        UgsMemberSuperLevelExample ugsMemberSuperLevelExample = new UgsMemberSuperLevelExample();
        ugsMemberSuperLevelExample.createCriteria().andMemberIdEqualTo(memberInfo.getMemberId()).andTenantCodeEqualTo(memberInfo.getTenantCode()).andStatusEqualTo("0").andEndTimeGreaterThan(new Date());
        List<UgsMemberSuperLevel> ugsMemberSuperLevels = ugsMemberSuperLevelService.selectByExample(ugsMemberSuperLevelExample);
        return ugsMemberSuperLevels.stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public synchronized void updateMemberByUntying(Long subMemberId, Long masterMemberId, String tenantCode) {
        MemberInfo submember = memberInfoMapper.selectByPrimaryKey(subMemberId);
        MemberAccount subMemberAccount = memberAccountMapper.selectByPrimaryKey(subMemberId);
        MemberAccount masetMemberAccount = memberAccountMapper.selectByPrimaryKey(masterMemberId);

        //增加out记录
        EnterpriseSubmemberOut enterpriseSubmemberOut = new EnterpriseSubmemberOut();
        enterpriseSubmemberOut.setCreatedBy(String.valueOf(subMemberId));
        enterpriseSubmemberOut.setCreatedTime(new Date());
        enterpriseSubmemberOut.setTenantCode(tenantCode);
        enterpriseSubmemberOut.setBelongEnterpriseId(submember.getBelongEnterpriseId());
        enterpriseSubmemberOut.setOutTime(new Date());
        enterpriseSubmemberOut.setSubmemberId(submember.getMemberId());
        enterpriseSubmemberOut.setStatus("0");
        enterpriseSubmemberOutService.insert(enterpriseSubmemberOut);

        //消除子会员数据
        submember.setMemberType(WebConstant.CON0);
        submember.setEnterpriseMemberId(null);
        submember.setBelongEnterpriseId(null);
        memberInfoMapper.updateByPrimaryKey(submember);

        //子账号解绑回收金额
        MemberAccountRecord subMemberAccountRecord = new MemberAccountRecord();
        subMemberAccountRecord.setTenantCode(tenantCode);
        subMemberAccountRecord.setMemberId(subMemberId);
        subMemberAccountRecord.setAccountType("1");
        subMemberAccountRecord.setRecordType("7");//金额回收
        subMemberAccountRecord.setResult(BigDecimal.ZERO);
        subMemberAccountRecord.setRemark("子账号解绑退回金额");
        subMemberAccountRecord.setCreatedTime(new Date());
        subMemberAccountRecord.setAmount(subMemberAccount.getEnterpriseAccount());
        subMemberAccountRecord.setLastUpdatedTime(new Date());
        memberAccountRecordMapper.insertSelective(subMemberAccountRecord);

        if (subMemberAccount.getEnterpriseAccount() == null || subMemberAccount.getEnterpriseAccount().compareTo(BigDecimal.ZERO) <= 0) {
            subMemberAccount.setEnterpriseAccount(BigDecimal.ZERO);
        } else {
            //回收企业余额
            if (masetMemberAccount != null) {
                masetMemberAccount.setEnterpriseAccount(masetMemberAccount.getEnterpriseAccount().add(subMemberAccount.getEnterpriseAccount()));
                subMemberAccount.setEnterpriseAccount(BigDecimal.ZERO);
            }
        }
        memberAccountMapper.updateByPrimaryKey(subMemberAccount);
        memberAccountMapper.updateByPrimaryKey(masetMemberAccount);

        //修改注销状态
        EnterpriseSubmember entSubmember = enterpriseSubmemberService.selectByPrimaryKey(subMemberId);
        entSubmember.setStatus(WebConstant.CON1);
        entSubmember.setLastUpdatedTime(new Date());
        entSubmember.setLastUpdatedBy(submember.getMemberId().toString());
        enterpriseSubmemberService.updateByPrimaryKeySelective(entSubmember);

        //删除有效的企业VIP记录
        //增加apply记录
        EnterpriseSubmemberApply enterpriseSubmemberApply = new EnterpriseSubmemberApply();
        enterpriseSubmemberApply.setSubmemberMobile(submember.getMobile());
        enterpriseSubmemberApply.setEnterpriseMemberId(masterMemberId);
        enterpriseSubmemberApply.setSubMemberId(submember.getMemberId());
        enterpriseSubmemberApply.setCreatedBy(String.valueOf(submember.getMemberId()));
        enterpriseSubmemberApply.setCreatedTime(new Date());
        enterpriseSubmemberApply.setSubmemberNickname("");
        enterpriseSubmemberApply.setEnterpriseMobile("");
        enterpriseSubmemberApply.setHeadImg(null);
        //'申请来源 0前台申请  1后台增加 默认0',
        enterpriseSubmemberApply.setApplySource("0");
        //申请类型 0申请加入企业主帐号 1申请注销 2申请冻结',
        enterpriseSubmemberApply.setApplyType("1");
        enterpriseSubmemberApply.setStatus("1");
        enterpriseSubmemberApply.setTenantCode(submember.getTenantCode());
        enterpriseSubmemberApplyService.insertSelective(enterpriseSubmemberApply);

        //增加record记录
        EnterpriseSubmemberRecord enterpriseSubmemberRecord = new EnterpriseSubmemberRecord();
        enterpriseSubmemberRecord.setEnterpriseId(submember.getBelongEnterpriseId());
        enterpriseSubmemberRecord.setCreatedBy(String.valueOf(subMemberId));
        enterpriseSubmemberRecord.setCreatedTime(new Date());
        enterpriseSubmemberRecord.setEnterpriseMemberId(subMemberId);
        enterpriseSubmemberRecord.setSubMemberId(subMemberId);
        enterpriseSubmemberRecord.setTenantCode(submember.getTenantCode());
        enterpriseSubmemberRecord.setRecordType("1");
        enterpriseSubmemberRecordService.insert(enterpriseSubmemberRecord);
    }

    @Override
    public MemberInfo selectMemberByAliUserId(String userId) {
        MemberInfoExample example=new MemberInfoExample();
        example.createCriteria().andAliUserIdEqualTo(userId);
        return memberInfoMapper.selectByExample(example).stream().findFirst().orElseGet(()->null);
    }

    @Override
    public void updateLogin(Long memberId) {
        memberInfoMapper.updateLogin(memberId);
    }

}
